package com.huan.config;

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;
@Component
public class CustomAuthenticationFailureHandler implements AuthenticationFailureHandler {

  private int maxAttempts = 5;
  private int lockDuration = 30; // minutes

  // 使用Map或数据库记录每个账号的失败次数
  private Map<String, Integer> failedAttempts;


  private void lockAccount(String username) {
  // 记录锁定时间
  failedAttempts.put(username, -1); 
  }

  @Override
  public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
    String username = httpServletRequest.getParameter("username");

    // 累加失败次数
    failedAttempts.put(username, failedAttempts.get(username)+1);

    if(failedAttempts.get(username) >= maxAttempts) {
      // 锁定账号
      lockAccount(username);
    }
  }
}
